package com.burst.reptile.modular.app.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.constant.HttpStatus;
import com.burst.reptile.common.exception.CustomException;
import com.burst.reptile.common.exception.user.CaptchaException;
import com.burst.reptile.common.exception.user.CaptchaExpireException;
import com.burst.reptile.common.utils.DateUtil;
import com.burst.reptile.common.utils.NumberUtils;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.file.FileUploadUtils;
import com.burst.reptile.common.utils.file.ImgUtils;
import com.burst.reptile.common.utils.file.VideoUtils;
import com.burst.reptile.common.utils.textreview.TextContent;
import com.burst.reptile.common.utils.zp.HtmlUtils;
import com.burst.reptile.framework.aspectj.lang.annotation.DelRes;
import com.burst.reptile.framework.aspectj.lang.annotation.Log;
import com.burst.reptile.framework.aspectj.lang.annotation.Msg;
import com.burst.reptile.framework.aspectj.lang.annotation.ReadContent;
import com.burst.reptile.framework.aspectj.lang.annotation.ReadMsg;
import com.burst.reptile.framework.aspectj.lang.enums.BusinessType;
import com.burst.reptile.framework.aspectj.lang.enums.MsgType;
import com.burst.reptile.framework.config.CrawlerConfig;
import com.burst.reptile.framework.constant.ConstantFactory;
import com.burst.reptile.framework.redis.RedisCache;
import com.burst.reptile.framework.security.LoginUser;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.framework.tencent.CosPutObject;
import com.burst.reptile.framework.web.controller.BaseController;
import com.burst.reptile.framework.web.result.LayuiResult;
import com.burst.reptile.framework.web.result.Result;
import com.burst.reptile.framework.web.result.ServiceResult;
import com.burst.reptile.modular.api.form.EditPhoneForm;
import com.burst.reptile.modular.api.form.EditPwdForm;
import com.burst.reptile.modular.api.form.QueryResForm;
import com.burst.reptile.modular.api.form.ResourcesForm;
import com.burst.reptile.modular.api.vo.BaseUser;
import com.burst.reptile.modular.api.vo.PublishRes;
import com.burst.reptile.modular.api.vo.QuestionVo;
import com.burst.reptile.modular.api.vo.ReplyVo;
import com.burst.reptile.modular.app.dto.ColumnDto;
import com.burst.reptile.modular.app.vo.CathListVo;
import com.burst.reptile.modular.app.vo.ChatMsgVo;
import com.burst.reptile.modular.app.vo.FollowVo;
import com.burst.reptile.modular.app.vo.VideoVo;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysUserService;
import com.burst.reptile.modular.web.entity.ZpAvatar;
import com.burst.reptile.modular.web.entity.ZpWebinfo;
import com.burst.reptile.modular.web.service.IZpAvatarService;
import com.burst.reptile.modular.web.service.IZpWebinfoService;
import com.burst.reptile.modular.zp.entity.ZpChatList;
import com.burst.reptile.modular.zp.entity.ZpChatMsg;
import com.burst.reptile.modular.zp.entity.ZpCity;
import com.burst.reptile.modular.zp.entity.ZpCollect;
import com.burst.reptile.modular.zp.entity.ZpColumn;
import com.burst.reptile.modular.zp.entity.ZpComment;
import com.burst.reptile.modular.zp.entity.ZpFeedback;
import com.burst.reptile.modular.zp.entity.ZpFormat;
import com.burst.reptile.modular.zp.entity.ZpHelpShop;
import com.burst.reptile.modular.zp.entity.ZpHistory;
import com.burst.reptile.modular.zp.entity.ZpLabel;
import com.burst.reptile.modular.zp.entity.ZpNotice;
import com.burst.reptile.modular.zp.entity.ZpQuestion;
import com.burst.reptile.modular.zp.entity.ZpQuestionType;
import com.burst.reptile.modular.zp.entity.ZpResources;
import com.burst.reptile.modular.zp.entity.ZpServiceItems;
import com.burst.reptile.modular.zp.entity.ZpVote;
import com.burst.reptile.modular.zp.service.IZpChatListService;
import com.burst.reptile.modular.zp.service.IZpChatMsgService;
import com.burst.reptile.modular.zp.service.IZpCityService;
import com.burst.reptile.modular.zp.service.IZpCollectService;
import com.burst.reptile.modular.zp.service.IZpColumnService;
import com.burst.reptile.modular.zp.service.IZpCommSupService;
import com.burst.reptile.modular.zp.service.IZpCommentService;
import com.burst.reptile.modular.zp.service.IZpFansService;
import com.burst.reptile.modular.zp.service.IZpFeedbackService;
import com.burst.reptile.modular.zp.service.IZpFollowService;
import com.burst.reptile.modular.zp.service.IZpFormatService;
import com.burst.reptile.modular.zp.service.IZpHelpShopService;
import com.burst.reptile.modular.zp.service.IZpHistoryService;
import com.burst.reptile.modular.zp.service.IZpLabelService;
import com.burst.reptile.modular.zp.service.IZpNoticeService;
import com.burst.reptile.modular.zp.service.IZpQuestionService;
import com.burst.reptile.modular.zp.service.IZpQuestionTypeService;
import com.burst.reptile.modular.zp.service.IZpResourcesService;
import com.burst.reptile.modular.zp.service.IZpServiceItemsService;
import com.burst.reptile.modular.zp.service.IZpVoteService;
import com.burst.reptile.modular.zp.warpper.ZpResourcesWrapper;
import com.burst.reptile.modular.zp.warpper.ZpWxCommentWrapper;
import com.hankcs.hanlp.HanLP;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/app/res")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpAppController extends BaseController {
	
	private static final Logger log = LoggerFactory.getLogger(ZpAppController.class);

	private final IZpResourcesService resourcesService;

	private final TokenService tokenService;

	private final ISysUserService userService;

	private final IZpVoteService voteService;

	private final IZpCommentService commentService;

	private final IZpCityService cityService;

	private final IZpFollowService followService;

	private final IZpFansService fansService;

	private final IZpCommSupService commSupService;

	private final CosPutObject cosPutObject;

	private final IZpWebinfoService webinfoService;

	private final IZpNoticeService noticeService;

	private final IZpCollectService collectService;

	private final IZpHistoryService historyService;

	private final IZpChatListService chatListService;

	private final IZpChatMsgService chatMsgService;

	private final IZpLabelService labelService;

	private final IZpHelpShopService helpShopService;

	private final IZpFeedbackService feedbackService;

	private final RedisCache redisCache;

	private final IZpAvatarService avatarService;

	private final IZpQuestionTypeService questionTypeService;

	private final IZpQuestionService questionService;
	
	private final IZpFormatService formatService;
	
	private final IZpServiceItemsService serviceItemsService;
	
	private final IZpColumnService columnService;
	
	/**
	 * 获取栏目
	 * @return
	 */
	@GetMapping("/colf")
	public Result<Object> colf(){
		QueryWrapper<ZpColumn> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("column_sort");
		List<ZpColumn> list = columnService.list(queryWrapper);
		List<ColumnDto> res = new ArrayList<>();
		if(ToolUtil.isNotEmpty(list)) {
			res = list.stream().filter(i -> {
				Integer columnId = i.getColumnId();
				if(columnId.equals(1) || columnId.equals(7)) {
					return false;
				}
				return true;
			}).map(i -> {
				ColumnDto dto = new ColumnDto();
				dto.setIcon(i.getColIcon());
				dto.setId(i.getColumnId());
				dto.setName(i.getColumnName());
				return dto;
			}).collect(Collectors.toList());
		}
		return Result.success(res);
	}
	
	/**
	 * 获取栏目
	 * @return
	 */
	@GetMapping("/col")
	public Result<Object> col(){
		QueryWrapper<ZpColumn> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("column_sort");
		List<ZpColumn> list = columnService.list(queryWrapper);
		List<ColumnDto> res = new ArrayList<>();
		if(ToolUtil.isNotEmpty(list)) {
			res = list.stream().map(i -> {
				ColumnDto dto = new ColumnDto();
				dto.setIcon(i.getColIcon());
				dto.setId(i.getColumnId());
				dto.setName(i.getColumnName());
				return dto;
			}).collect(Collectors.toList());
		}
		return Result.success(res);
	}
	
	/**
	 * 所有广告图
	 * @param id
	 * @return
	 */
	@GetMapping("/bimgall")
	public Result<Object> bimgall(){
		Map <String, List<String>> map = new HashMap<>();
		// 铺友圈
		List<String> list1 = new ArrayList<>();
		list1.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/001pyq.jpg?v=20201012");
		list1.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/002pyq.jpg?v=20201012");
		map.put("pyq", list1);
		// 商铺租转
		List<String> list2 = new ArrayList<>();
		list2.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/001zz.jpg?v=20201012");
		list2.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/002zz.jpg?v=20201012");
		map.put("spzz", list2);
		// 商铺出售
		List<String> list3 = new ArrayList<>();
		list3.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/001cs.jpg?v=20201012");
		list3.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/002cs.jpg?v=20201012");
		map.put("spcs", list3);
		// 商户服务
		List<String> list4 = new ArrayList<>();
		list4.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/001fw.jpg?v=20201012");
		list4.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/002fw.jpg?v=20201012");
		map.put("shfw", list4);
		// 商户活动
		List<String> list5 = new ArrayList<>();
		list5.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/001hd.jpg?v=20201012");
		list5.add("https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/002hd.jpg?v=20201012");
		map.put("shhd", list5);
		return Result.success(map);
	}
	
	/**
	 * 区域
	 * @return
	 */
	@GetMapping("/area")
	public Result<Object> area(){
		return Result.success(cityService.children(tokenService.getCitySite()));
	}
	
	/**
	 * 获取业态
	 * @return
	 */
	@GetMapping("/acs")
	public Result<Object> activity(){
		List<ZpFormat> list = formatService.list();
		List<ColumnDto> res = new ArrayList<>();
		if(ToolUtil.isNotEmpty(list)) {
			res = list.stream().map(i -> {
				ColumnDto dto = new ColumnDto();
				dto.setId(i.getFormatId());
				dto.setName(i.getFormatName());
				return dto;
			}).collect(Collectors.toList());
		}
		return Result.success(res);
	}
	
	/**
	 * 获取服务
	 * @return
	 */
	@GetMapping("/fuwu")
	public Result<Object> fuwu(){
		List<ZpServiceItems> list = serviceItemsService.list();
		List<ColumnDto> res = new ArrayList<>();
		if(ToolUtil.isNotEmpty(list)) {
			res = list.stream().map(i -> {
				ColumnDto dto = new ColumnDto();
				dto.setId(i.getSid());
				dto.setName(i.getName());
				return dto;
			}).collect(Collectors.toList());
		}
		return Result.success(res);
	}

	/**
	 * 推荐文章
	 * 
	 * @param cid
	 * @return
	 */
	@GetMapping("/rec")
	public LayuiResult<Object> rec(@RequestParam(required = false) Integer cid, 
			@RequestParam(required = false) String county, 
			@RequestParam(required = false) Integer formatId, 
			@RequestParam(required = false) Integer serviceItems, 
			@RequestParam(required = false) Integer sortt) {
		// 推荐文章
		Page<ZpResources> list = new Page<>();
		Page<ZpResources> pages = startPage();
		ZpResources zpResources = new ZpResources();
		if (ToolUtil.isEmpty(cid)) {
			return LayuiResult.success(false, 0, null);
		}
		if(StrUtil.isNotEmpty(county)) {
			zpResources.setCounty(county);
		}
		if(ToolUtil.isNotEmpty(formatId)) {
			zpResources.setFormatId(formatId);
		}
		if(ToolUtil.isNotEmpty(serviceItems)) {
			zpResources.setServiceItems(serviceItems);
		}
		if(ToolUtil.isNotEmpty(sortt)) {
			zpResources.setSortt(sortt);
		}
		if (cid.equals(0)) {
			zpResources.setRec("1");
			zpResources.setColumnId(1); // 推荐铺友圈的
		} else {
			zpResources.setColumnId(cid);
		}
		zpResources.setDraft("0");
		zpResources.setCity(tokenService.getCitySite());
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			list = resourcesService.pageList(pages, zpResources);
			if (list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}else {
			list = resourcesService.pageList(pages, zpResources);
			if (list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}
		new ZpResourcesWrapper(list).wrap();
		return LayuiResult.success(list.hasNext(), list.getTotal(), list.getRecords());
	}

	/**
	 * 活动列表
	 * 
	 * @param cid
	 * @return
	 */
	@GetMapping("/activity")
	public LayuiResult<Object> activity(@RequestParam(required = false) Integer cid, 
			@RequestParam(required = false) String county,
			@RequestParam(required = false) Integer sortt) {
		// 推荐文章
		Page<ZpResources> list = new Page<>();
		Page<ZpResources> pages = startPage();
		ZpResources zpResources = new ZpResources();
		if (ToolUtil.isEmpty(cid)) {
			return LayuiResult.success(false, 0, null);
		}
		if(StrUtil.isNotEmpty(county)) {
			zpResources.setCounty(county);
		}
		if(ToolUtil.isNotEmpty(sortt)) {
			zpResources.setSortt(sortt);
		}
		zpResources.setColumnId(7);
		if (!cid.equals(0)) {
			zpResources.setFormatId(cid);
		}
		zpResources.setDraft("0");
		zpResources.setCity(tokenService.getCitySite());
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			list = resourcesService.pageList(pages, zpResources);
			if (list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		} else {
			list = resourcesService.pageList(pages, zpResources);
			if (list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(pages, zpResources);
			}
		}
		new ZpResourcesWrapper(list).wrap();
		return LayuiResult.success(list.hasNext(), list.getTotal(), list.getRecords());
	}

	/**
	 * 内容详情
	 * 
	 * @param id ID
	 * @return
	 */
	@GetMapping("/details/{id}")
	@ReadContent
	public Result<Object> details(@PathVariable String id) {
		ZpResources resources = resourcesService.getById(id);
		if (ToolUtil.isNotEmpty(resources) && StrUtil.equals(resources.getDraft(), "0")) {
			String tags = resources.getTags();
			String pictureSet = resources.getPictureSet();
			Integer serviceItems = resources.getServiceItems();
			String county = resources.getCounty();
			String city = resources.getCity();
			LocalDateTime updateTime = resources.getUpdateTime();
			if (StrUtil.isNotEmpty(tags)) {
				resources.setTbs(JSONObject.parseArray(tags, String.class));
			}
			if (StrUtil.isNotEmpty(pictureSet)) {
				resources.setImgs(JSONObject.parseArray(pictureSet, String.class));
			}
			if (ToolUtil.isNotEmpty(updateTime)) {
				resources.setTime(DateUtil.timeToFormat(updateTime));
			}
			if (ToolUtil.isNotEmpty(serviceItems)) {
				// 服务项目名称
				resources.setServiceItemsName(ConstantFactory.me().getserviceItemsName(serviceItems));
			}
			String countyName = null;
			if (StrUtil.isNotEmpty(city)) {
				countyName = ConstantFactory.me().getAddressName(city);
			}
			if (StrUtil.isNotEmpty(county)) {
				String addressName = ConstantFactory.me().getAddressName(county);
				if (StrUtil.isNotEmpty(countyName) && StrUtil.isNotEmpty(addressName)) {
					countyName = countyName + "-" + addressName;
					;
				} else if (StrUtil.isNotEmpty(addressName)) {
					if (StrUtil.isNotEmpty(addressName)) {
						countyName = "-" + addressName;
					}
				}
				resources.setCountyName(countyName);
			}
			// 作者信息
			Long userId = resources.getUserId();
			SysUser user = userService.getById(userId);
			if (ToolUtil.isNotEmpty(user)) {
				user.setFans(ConstantFactory.me().getFans(user.getUserId()));
			}
			// 文章和我的关系
			LoginUser loginUser = tokenService.getWxUser();
			if (ToolUtil.isNotEmpty(loginUser)) {
				Long loginUserId = loginUser.getUser().getUserId();
				// 是否点赞 是否收藏
				int voteCount = voteService.count(new QueryWrapper<ZpVote>().eq("user_id", loginUserId).eq("article_id",
						resources.getArticleId()));
				resources.setVote(voteCount > 0);
				int collectCount = collectService.count(new QueryWrapper<ZpCollect>().eq("user_id", loginUserId)
						.eq("article_id", resources.getArticleId()));
				resources.setCollect(collectCount > 0);
				// 是否关注
				if (!userId.equals(loginUserId)) {
					user.setMutual(ConstantFactory.me().mutual(userId, loginUserId));
				}
			}
			resources.setUser(user);
			resources.setCommentNum(commentService.getCommentNum(id));
			// 阅读量格式化
			resources.setReadSizeFormat(NumberUtils.amountConversion(resources.getReadSize()));
			// 点赞量格式化
			resources.setVoteSizeFormat(NumberUtils.amountConversion(resources.getVoteSize()));
			// 收藏量格式化
			resources.setCollectSizeFormat(NumberUtils.amountConversion(resources.getCollectSize()));
			String content = resources.getContent();
			String html = HtmlUtils.removeVideoAttr(content);
			resources.setContent(html);
		} else {
			return Result.error();
		}
		// 类似推荐
		Page<ZpResources> page = new Page<>(1, 5);
		Page<ZpResources> pagelist = resourcesService.recType(page, resources.getArticleId(), resources.getKeywords());
		new ZpResourcesWrapper(pagelist).wrap();
		Map<String, Object> map = new HashMap<>();
		map.put("res", resources);
		map.put("rec", pagelist.getRecords());
		return Result.success(map);
	}

	/**
	 * 获取城市
	 * 
	 * @param adcode
	 * @return
	 */
	@GetMapping("/getCity")
	public Result<Object> getCity(@RequestParam(required = false) String adcode) {
		ZpCity byId = cityService.getById(adcode);
		ZpCity city = null;
		if (ToolUtil.isNotEmpty(byId)) {
			String levelType = byId.getLevelType();
			if (StrUtil.equals(levelType, "3")) {
				String parentId = byId.getParentId();
				city = cityService.getById(parentId);
			}
		}
		return Result.success(city);
	}

	/**
	 * 获取城市
	 * 
	 * @return
	 */
	@GetMapping("/city")
	public Result<Object> city() {
		List<ZpCity> children = cityService
				.list(new QueryWrapper<ZpCity>().eq("level_type", "2").eq("disabled", "0").orderByAsc("first_char"));
		List<List<ZpCity>> groupList = new ArrayList<>();
		if (ToolUtil.isNotEmpty(children)) {
			children.stream().collect(Collectors.groupingBy(ZpCity::getFirstChar, Collectors.toList()))
					.forEach((name, city) -> {
						groupList.add(city);
					});
		}
		return Result.success(groupList);
	}

	/**
	 * 评论列表
	 * 
	 * @return
	 */
	@GetMapping("/comment/{id}")
	public LayuiResult<Object> comment(@PathVariable String id) {
		Page<ZpComment> page = startPage();
		if (StrUtil.isEmpty(id)) {
			return LayuiResult.success(page.getTotal(), page.getRecords());
		}
		Page<ZpComment> pageList = commentService.pageList(page, id, null);
		new ZpWxCommentWrapper(pageList).wrap();
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), pageList.getRecords());
	}

	/**
	 * 回复列表
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/replys/{id}")
	public Result<Object> replys(@PathVariable Long id) {
		List<ZpComment> selectList = commentService
				.list(new QueryWrapper<ZpComment>().eq("acid", id).eq("ctype", "1").orderByDesc("create_time"));
		List<ReplyVo> list = new ArrayList<>();
		if (ToolUtil.isNotEmpty(selectList)) {
			list = selectList.stream().map(i -> {
				Long userId = i.getUserId();
				Long touserId = i.getTouserId();
				ReplyVo reply = new ReplyVo();
				reply.setCid(i.getCid());
				reply.setPcid(i.getPcid());
				reply.setAcid(i.getAcid());
				reply.setContent(i.getContent());
				reply.setTcontent(i.getTcontent());
				reply.setCreateTime(i.getCreateTime());
				reply.setLikes(i.getLikes());
				SysUser user = userService.getById(userId);
				BaseUser roperties = new BaseUser();
				BeanUtil.copyProperties(user, roperties);
				reply.setRespondents(roperties);
				SysUser u = userService.getById(touserId);
				BaseUser touserUser = new BaseUser();
				BeanUtil.copyProperties(u, touserUser);
				reply.setUser(touserUser);
				reply.setUserId(i.getUserId());
				LoginUser wxUser = tokenService.getWxUser();
				if (ToolUtil.isNotEmpty(wxUser)) {
					Long loginUserId = wxUser.getUser().getUserId();
					reply.setOwn(userId.equals(loginUserId));
					reply.setSupport(ConstantFactory.me().isSupport(loginUserId, i.getCid()));
				}
				reply.setTime(DateUtil.timeToFormat(i.getCreateTime()));
				reply.setLikes(ConstantFactory.me().getCommentLikes(i.getCid()));
				return reply;
			}).collect(Collectors.toList());
		}
		return Result.success(list);
	}

	/**
	 * 评论点赞
	 * 
	 * @param id 评论ID
	 * @return
	 */
	@PostMapping("/praise/{id}")
	public Result<Object> praise(@PathVariable Long id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(commSupService.wxpraise(id, loginUser.getUser().getUserId()));

	}

	/**
	 * 取消评论点赞
	 * 
	 * @param id 评论ID
	 * @return
	 */
	@PostMapping("/unpraise/{id}")
	public Result<Object> unpraise(@PathVariable Long id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(commSupService.wxunpraise(id, loginUser.getUser().getUserId()));
	}

	/**
	 * 添加评论
	 * 
	 * @param content
	 * @return
	 */
	@PostMapping("/addcomment")
	@Msg(businessType = MsgType.COMMENT)
	public Result<Object> addcomment(@Validated @RequestBody ZpComment comment) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		String content = comment.getContent();
		boolean examineText = TextContent.examineText(content);
		if (examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		comment.setCtype("0");
		comment.setUserId(loginUser.getUser().getUserId());
		return Result.success(commentService.wxAdd(comment));
	}

	/**
	 * 添加回复评论
	 * 
	 * @param content
	 * @return
	 */
	@PostMapping("/addreply")
	public Result<Object> addreply(@Validated @RequestBody ZpComment comment) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		String content = comment.getContent();
		boolean examineText = TextContent.examineText(content);
		if (examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		comment.setCtype("1");
		comment.setUserId(loginUser.getUser().getUserId());
		return Result.success(commentService.wxAdd(comment));
	}

	/**
	 * 删除评论
	 * 
	 * @param content
	 * @return
	 */
	@PostMapping("/delcomment/{id}")
	public Result<Object> addcomment(@PathVariable String id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(commentService.wxdel(id, loginUser.getUser().getUserId()));
	}

	/**
	 * 回复列表
	 * 
	 * @return
	 */
	@GetMapping("/reply/{id}")
	public LayuiResult<Object> reply(@PathVariable String id) {
		Page<ZpComment> page = startPage();
		Page<ZpComment> pageList = commentService.pageReplyList(page, id);
		List<ZpComment> records = pageList.getRecords();
		List<ReplyVo> list = new ArrayList<>();
		if (ToolUtil.isNotEmpty(records)) {
			list = records.stream().map(i -> {
				Long userId = i.getUserId();
				Long touserId = i.getTouserId();
				ReplyVo reply = new ReplyVo();
				reply.setCid(i.getCid());
				reply.setContent(i.getContent());
				reply.setCreateTime(i.getCreateTime());
				reply.setLikes(i.getLikes());
				SysUser user = userService.getById(userId);
				BaseUser roperties = new BaseUser();
				BeanUtil.copyProperties(user, roperties);
				reply.setRespondents(roperties);
				SysUser u = userService.getById(touserId);
				BaseUser touserUser = new BaseUser();
				BeanUtil.copyProperties(u, touserUser);
				reply.setUser(touserUser);
				reply.setUserId(i.getUserId());
				LoginUser wxUser = tokenService.getWxUser();
				if (ToolUtil.isNotEmpty(wxUser)) {
					Long loginUserId = wxUser.getUser().getUserId();
					reply.setOwn(userId.equals(loginUserId));
					reply.setSupport(ConstantFactory.me().isSupport(loginUserId, i.getCid()));
				}
				reply.setTime(DateUtil.timeToFormat(i.getCreateTime()));
				reply.setLikes(ConstantFactory.me().getCommentLikes(i.getCid()));
				return reply;
			}).collect(Collectors.toList());
		}
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), list);
	}

	/**
	 * 点赞
	 * 
	 * @param id 文章ID
	 * @return
	 */
	@PostMapping("/vote/{id}")
	@Msg(businessType = MsgType.GIVE)
	public Result<Object> vote(@PathVariable String id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long userId = loginUser.getUser().getUserId();
		ZpResources resources = resourcesService.getById(id);
		if (ToolUtil.isEmpty(resources)) {
			throw new CustomException("文章已被删除了", HttpStatus.MOVED_PERM);
		}
		// 添加点赞信息
		int res = voteService.add(userId, resources);
		return Result.success(res);
	}

	/**
	 * 取消点赞
	 * 
	 * @param id 文章ID
	 * @return
	 */
	@PostMapping("/vote_cancel/{id}")
	public Result<Object> voteCancel(@PathVariable String id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long userId = loginUser.getUser().getUserId();
		// 移除点赞信息
		int res = voteService.del(userId, Long.valueOf(id));
		return Result.success(res);
	}

	/**
	 * 收藏
	 * 
	 * @param id 文章ID
	 * @return
	 */
	@PostMapping("/collect/{id}")
	@Msg(businessType = MsgType.COLLECTION)
	public Result<Object> collect(@PathVariable String id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long userId = loginUser.getUser().getUserId();
		ZpResources resources = resourcesService.getById(id);
		if (ToolUtil.isEmpty(resources)) {
			throw new CustomException("文章已被删除了", HttpStatus.MOVED_PERM);
		}
		// 添加收藏信息
		int res = collectService.add(userId, resources);
		return Result.success(res);
	}

	/**
	 * 取消收藏
	 * 
	 * @param id 文章ID
	 * @return
	 */
	@PostMapping("/collect_cancel/{id}")
	public Result<Object> collect_cancel(@PathVariable String id) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long userId = loginUser.getUser().getUserId();
		int res = collectService.del(userId, Long.valueOf(id));
		return Result.success(res);
	}

	/**
	 * 关注用户
	 * 
	 * @param userId 用户ID
	 * @return
	 */
	@PostMapping("/follow/{userId}")
	@Msg(businessType = MsgType.FANS)
	public Result<Object> follow(@PathVariable Long userId) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long auserId = loginUser.getUser().getUserId();
		if (userId.equals(auserId)) {
			throw new CustomException("禁止操作", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(followService.wxfollow(userId, auserId));
	}

	/**
	 * 取关
	 * 
	 * @param userId 用户ID
	 * @return
	 */
	@PostMapping("/takeOff/{userId}")
	public Result<Object> takeOff(@PathVariable Long userId) {
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long auserId = loginUser.getUser().getUserId();
		if (userId.equals(auserId)) {
			throw new CustomException("禁止操作", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(followService.wxtakeOff(userId, auserId));
	}

	/**
	 * tinymce 上传图片到腾讯云COS
	 * 
	 * @param uploadFile
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@PostMapping("/img")
	public Result<Object> tinyimg(MultipartFile uploadFile, HttpServletRequest request, @RequestParam String uuid)
			throws IllegalStateException, IOException {
		if (ToolUtil.isEmpty(uploadFile)) {
			return Result.error(HttpStatus.BAD_REQUEST, "请上传文件");
		}
		String bucketName = CrawlerConfig.getBucketName();
		String extension = FileUploadUtils.getExtension(uploadFile);
		String fileName = IdUtil.simpleUUID() + "." + extension;
		String key = Constants.IMG_KEY + fileName;
		boolean watermark = CrawlerConfig.getWatermark();
		if (watermark) {
			String uploadPath = CrawlerConfig.getUploadPath();
			String destImageFile = uploadPath + File.separator + IdUtil.simpleUUID() + "." + extension;
			// 上传文件路径
			String filePath = uploadPath + File.separator + fileName;
			// 保存
			uploadFile.transferTo(new File(filePath));
			ImgUtils.myPressImage(filePath, destImageFile, CrawlerConfig.getPressImgFile());
			cosPutObject.localPut(destImageFile, CrawlerConfig.getBucketName(), key);
			File desFile = new File(destImageFile);
			if (desFile.exists()) {
				desFile.delete();
			}
		} else {
			cosPutObject.put(uploadFile, bucketName, key, uuid);
		}
		return Result.success(Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/"
				+ Constants.IMG_KEY + fileName);
	}

	/**
	 * 获取用户已发布内容
	 * 
	 * @return
	 */
	@GetMapping("/pulishlist")
	public LayuiResult<Object> pulishlist(@RequestParam(required = false) Integer cid,
			@RequestParam(required = false) String draft) {
		Page<ZpResources> page = startPage();
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			return LayuiResult.success(false, 0, page.getRecords());
		}
		QueryResForm query = new QueryResForm();
		if (ToolUtil.isNotEmpty(cid)) {
			query.setColumnId(cid);
		}
		query.setUserId(loginUser.getUser().getUserId());
		if (StrUtil.isNotEmpty(draft)) {
			query.setDraft(draft);
		}
		Page<ZpResources> myPageList = resourcesService.myPageList(page, query);
		List<ZpResources> records = myPageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				// 是否点赞
				int voteCount = voteService.count(new QueryWrapper<ZpVote>()
						.eq("user_id", loginUser.getUser().getUserId()).eq("article_id", i.getArticleId()));
				i.setVote(voteCount > 0);
				i.setCommentNum(commentService.getCommentNum(i.getArticleId().toString()));
				// 阅读量格式化
				i.setReadSizeFormat(NumberUtils.amountConversion(i.getReadSize()));
				// 点赞量格式化
				i.setVoteSizeFormat(NumberUtils.amountConversion(i.getVoteSize()));
				String pictureSet = i.getPictureSet();
				if (StrUtil.isNotEmpty(pictureSet)) {
					// 图片数据封装
					i.setImgs(JSONObject.parseArray(pictureSet, String.class));
				}
				i.setUser(userService.getById(i.getUserId()));
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
				i.setTime(DateUtil.timeToFormat(i.getUpdateTime()));
			});
		}

		return LayuiResult.success(myPageList.hasNext(), myPageList.getTotal(), records);
	}

	/**
	 * 获取用户已发布内容
	 * 
	 * @return
	 */
	@GetMapping("/userpulishlist")
	public LayuiResult<Object> pulishlist(@RequestParam(required = false) Long userId,
			@RequestParam(required = false) Integer cid) {
		if (ToolUtil.isEmpty(userId)) {
			throw new CustomException("请求错误");
		}
		LoginUser wxUser = tokenService.getWxUser();

		Page<ZpResources> page = startPage();
		QueryResForm query = new QueryResForm();
		if (ToolUtil.isNotEmpty(cid)) {
			query.setColumnId(cid);
		}
		query.setUserId(userId);
		query.setDraft("0");
		Page<ZpResources> myPageList = resourcesService.myPageList(page, query);
		List<ZpResources> records = myPageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				// 是否点赞
				if (ToolUtil.isNotEmpty(wxUser)) {
					int voteCount = voteService.count(new QueryWrapper<ZpVote>()
							.eq("user_id", wxUser.getUser().getUserId()).eq("article_id", i.getArticleId()));
					i.setVote(voteCount > 0);
				}
				i.setCommentNum(commentService.getCommentNum(i.getArticleId().toString()));
				// 阅读量格式化
				i.setReadSizeFormat(NumberUtils.amountConversion(i.getReadSize()));
				// 点赞量格式化
				i.setVoteSizeFormat(NumberUtils.amountConversion(i.getVoteSize()));
				String pictureSet = i.getPictureSet();
				if (StrUtil.isNotEmpty(pictureSet)) {
					// 图片数据封装
					i.setImgs(JSONObject.parseArray(pictureSet, String.class));
				}
				i.setUser(userService.getById(i.getUserId()));
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
				i.setTime(DateUtil.timeToFormat(i.getUpdateTime()));
			});
		}

		return LayuiResult.success(myPageList.hasNext(), myPageList.getTotal(), records);
	}

	/**
	 * 删除资源
	 * 
	 * @param id 资源ID
	 * @return
	 */
	@PostMapping("/del/{id}")
	@Log(title = "删除资源", businessType = BusinessType.DELETE)
	@DelRes
	public Result<Object> del(@PathVariable String id) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(resourcesService.wxdel(id, wxUser.getUser().getUserId()));
	}

	/**
	 * 获取用户已发布内容
	 * 
	 * @return
	 */
	@GetMapping("/createlist")
	public LayuiResult<Object> createlist() {
		Page<ZpResources> page = startPage();
		LoginUser loginUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(loginUser)) {
			return LayuiResult.success(false, 0, page.getRecords());
		}
		QueryResForm query = new QueryResForm();
		query.setUserId(loginUser.getUser().getUserId());
		Page<ZpResources> myPageList = resourcesService.myCreatePageList(page, query);
		List<ZpResources> records = myPageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				// 是否点赞
				int voteCount = voteService.count(new QueryWrapper<ZpVote>()
						.eq("user_id", loginUser.getUser().getUserId()).eq("article_id", i.getArticleId()));
				i.setVote(voteCount > 0);
				i.setCommentNum(commentService.getCommentNum(i.getArticleId().toString()));
				// 阅读量格式化
				i.setReadSizeFormat(NumberUtils.amountConversion(i.getReadSize()));
				// 点赞量格式化
				i.setVoteSizeFormat(NumberUtils.amountConversion(i.getVoteSize()));
				String pictureSet = i.getPictureSet();
				if (StrUtil.isNotEmpty(pictureSet)) {
					// 图片数据封装
					i.setImgs(JSONObject.parseArray(pictureSet, String.class));
				}
				i.setUser(userService.getById(i.getUserId()));
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
				i.setTime(DateUtil.timeToFormat(i.getUpdateTime()));
			});
		}

		return LayuiResult.success(myPageList.hasNext(), myPageList.getTotal(), records);
	}

	/**
	 * 设为仅我可见
	 * 
	 * @param id 资源ID
	 * @return
	 */
	@PostMapping("/withdraw/{id}")
	@Log(title = "设为仅我可见", businessType = BusinessType.UPDATE)
	public Result<Object> withdraw(@PathVariable String id) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		ZpResources byId = resourcesService.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			return Result.error("资源不存在！");
		}
		Long userId = byId.getUserId();

		Long loginUserId = wxUser.getUser().getUserId();
		if (loginUserId.equals(userId)) {
			byId.setDraft("2");
			return Result.success(resourcesService.updateById(byId));
		}
		return Result.error("禁止操作");
	}

	/**
	 * 设为公开
	 * 
	 * @param id 资源ID
	 * @return
	 */
	@PostMapping("/recovery/{id}")
	@Log(title = "设为公开", businessType = BusinessType.UPDATE)
	public Result<Object> recovery(@PathVariable String id) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		ZpResources byId = resourcesService.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			return Result.error("资源不存在！");
		}
		Long userId = byId.getUserId();
		Long loginUserId = wxUser.getUser().getUserId();
		if (loginUserId.equals(userId)) {
			byId.setDraft("0");
			return Result.success(resourcesService.updateById(byId));
		}
		return Result.error("禁止操作");
	}

	/**
	 * 发布文章接口
	 * 
	 * @param resources
	 * @return
	 */
	@PostMapping("/publish")
	@Log(title = "发布资源", businessType = BusinessType.INSERT)
	public Result<Object> publish(@Validated @RequestBody ResourcesForm resources) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		boolean title = TextContent.examineText(resources.getTitle());
		if (title) {
			return Result.error("发布内容含敏感词汇");
		}
		String content = resources.getContentText();
		boolean examineText = TextContent.examineText(content);
		if (examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		resources.setUserId(wxUser.getUser().getUserId());
		PublishRes publishRes = resourcesService.wxadd(resources);
		return Result.success(publishRes);
	}
	
	/**
	 * 更新文章接口
	 * 
	 * @param resources
	 * @return
	 */
	@PostMapping("/editres")
	@Log(title = "更新资源", businessType = BusinessType.UPDATE)
	public Result<Object> update(@Validated @RequestBody ResourcesForm resources) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		boolean title = TextContent.examineText(resources.getTitle());
		if(title) {
			return Result.error("发布内容含敏感词汇");
		}
		boolean examineText = TextContent.examineText(resources.getContentText());
		if(examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		resources.setDraft("0");
		PublishRes publishRes = resourcesService.wxupdate(wxUser.getUser(), resources);
		return Result.success(publishRes);
	}

	/**
	 * 相关协议
	 * 
	 * @param id 协议类型
	 * @return
	 */
	@GetMapping("/agreement")
	public Result<Object> agreement(@RequestParam(required = false) String id) {
		ZpWebinfo zpWebinfo = webinfoService.getZpWebinfo(id);
		if (ToolUtil.isEmpty(zpWebinfo)) {
			return Result.error("暂无相关协议");
		}
		return Result.success(zpWebinfo);
	}

	/**
	 * 搜索结果加载更多
	 * 
	 * @param format 所属形态
	 * @param region 所在区域
	 * @param page   页数
	 * @param limit  获取数量
	 * @return
	 */
	@GetMapping("/searchkey")
	public LayuiResult<Object> searchkey(@RequestParam(required = false) String keyword,
			@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
		Page<ZpResources> pagelist = new Page<>();
		List<Map<String, String>> collect = new ArrayList<>();
		if (StrUtil.isNotEmpty(keyword)) {
			List<String> ik = HanLP.extractKeyword(keyword, 3);
			pagelist = resourcesService.searchkey(new Page<ZpResources>(1, 10), keyword, ik);
			collect = pagelist.getRecords().stream().map(i -> {
				Map<String, String> map = new HashMap<>();
				map.put("title", i.getTitle());
				map.put("htitle",
						StrUtil.replace(i.getTitle(), keyword, "<span style='color:#ed4040;'>" + keyword + "</span>"));
				map.put("id", i.getArticleId().toString());
				return map;
			}).collect(Collectors.toList());
		}
		return LayuiResult.success(pagelist.hasNext(), pagelist.getTotal(), collect);
	}

	/**
	 * 搜索结果加载更多
	 * 
	 * @param format 所属形态
	 * @param region 所在区域
	 * @param page   页数
	 * @param limit  获取数量
	 * @return
	 */
	@GetMapping("/search")
	public LayuiResult<Object> search(@RequestParam(required = false) String keyword,
			@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
		Page<ZpResources> pagelist = new Page<>();
		List<ZpResources> records = new ArrayList<>();
		if (StrUtil.isNotEmpty(keyword)) {
			List<String> ik = HanLP.extractKeyword(keyword, 3);
			pagelist = resourcesService.appsearch(page, limit, keyword, ik);
			new ZpResourcesWrapper(pagelist).wrap();
			records = pagelist.getRecords();
			if (ToolUtil.isNotEmpty(records)) {
				records.forEach(i -> {
					String title = i.getTitle();
					String summary = i.getSummary();
					title = StrUtil.replace(title, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					summary = StrUtil.replace(summary, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					if (ToolUtil.isNotEmpty(ik)) {
						for (String str : ik) {
							title = StrUtil.replace(title, str, "<span style='color:#ff4200;'>" + str + "</span>");
							summary = StrUtil.replace(summary, str, "<span style='color:#ff4200;'>" + str + "</span>");
							if (str.matches(".*[a-zA-z].*")) {
								String swapCase = StrUtil.swapCase(str);
								title = StrUtil.replace(title, swapCase,
										"<span style='color:#ff4200;'>" + swapCase + "</span>");
								summary = StrUtil.replace(summary, swapCase,
										"<span style='color:#ff4200;'>" + swapCase + "</span>");
							}
						}
					}
					i.setTitle(title);
					i.setSummary(summary);
					// 评论数
					i.setCommentNum(ConstantFactory.me().getCommentNum(i.getArticleId()));
					// 发布时间封装
					i.setTime(DateUtil.timeToFormat(i.getUpdateTime()));
					i.setUser(userService.getById(i.getUserId()));
					String pictureSet = i.getPictureSet();
					if (StrUtil.isNotEmpty(pictureSet)) {
						// 图片数据封装
						i.setImgs(JSONObject.parseArray(pictureSet, String.class));
					}
				});
			}
		}
		return LayuiResult.success(pagelist.hasNext(), pagelist.getTotal(), records);
	}

	/**
	 * 消息列表
	 * 
	 * @param type
	 * @return
	 */
	@GetMapping("/msglist")
	@ReadMsg
	public LayuiResult<Object> msglist(@RequestParam(required = false) String type) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Page<ZpNotice> page = startPage();
		ZpNotice notice = new ZpNotice();
		notice.setRelationUser(wxUser.getUser().getUserId());
		notice.setNoticeType(type);
		notice.setNoticeStatus("0");
		Page<ZpNotice> pageList = noticeService.pageList(page, notice);
		List<ZpNotice> records = pageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				i.setFormatTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
				if (ToolUtil.isNotEmpty(i.getUserId())) {
					SysUser byId = userService.getById(i.getUserId());
					byId.setMutual(ConstantFactory.me().mutual(i.getUserId(), wxUser.getUser().getUserId()));
					i.setUser(byId);
				}
				if (ToolUtil.isNotEmpty(i.getArticleId())) {
					i.setRes(resourcesService.getById(i.getArticleId()));
				}

			});
		}
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), pageList.getRecords());
	}

	/**
	 * 评论列表
	 * 
	 * @return
	 */
	@GetMapping("/commentlist")
	public LayuiResult<Object> commentlist() {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Page<ZpComment> page = startPage();
		ZpComment comment = new ZpComment();
		comment.setUserId(wxUser.getUser().getUserId());
		Page<ZpComment> pageList = commentService.pageList(page, comment);
		List<ZpComment> records = pageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				ZpResources res = resourcesService.getById(i.getArticleId());
				if (ToolUtil.isNotEmpty(res)) {
					// 是否点赞
					int voteCount = voteService.count(new QueryWrapper<ZpVote>()
							.eq("user_id", wxUser.getUser().getUserId()).eq("article_id", res.getArticleId()));
					res.setVote(voteCount > 0);
					res.setCommentNum(commentService.getCommentNum(res.getArticleId().toString()));
					// 阅读量格式化
					res.setReadSizeFormat(NumberUtils.amountConversion(res.getReadSize()));
					// 点赞量格式化
					res.setVoteSizeFormat(NumberUtils.amountConversion(res.getVoteSize()));
					String pictureSet = res.getPictureSet();
					if (StrUtil.isNotEmpty(pictureSet)) {
						// 图片数据封装
						res.setImgs(JSONObject.parseArray(pictureSet, String.class));
					}
					res.setUser(userService.getById(res.getUserId()));
					i.setRes(res);
				}
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
			});
		}
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), records);
	}

	/**
	 * 点赞列表
	 * 
	 * @return
	 */
	@GetMapping("/givelist")
	public LayuiResult<Object> givelist() {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Page<ZpVote> page = startPage();
		ZpVote vote = new ZpVote();
		vote.setUserId(wxUser.getUser().getUserId());
		Page<ZpVote> pageList = voteService.pageList(page, vote);
		List<ZpVote> records = pageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				ZpResources res = resourcesService.getById(i.getArticleId());
				if (ToolUtil.isNotEmpty(res)) {
					// 是否点赞
					int voteCount = voteService.count(new QueryWrapper<ZpVote>()
							.eq("user_id", wxUser.getUser().getUserId()).eq("article_id", res.getArticleId()));
					res.setVote(voteCount > 0);
					res.setCommentNum(commentService.getCommentNum(res.getArticleId().toString()));
					// 阅读量格式化
					res.setReadSizeFormat(NumberUtils.amountConversion(res.getReadSize()));
					// 点赞量格式化
					res.setVoteSizeFormat(NumberUtils.amountConversion(res.getVoteSize()));
					String pictureSet = res.getPictureSet();
					if (StrUtil.isNotEmpty(pictureSet)) {
						// 图片数据封装
						res.setImgs(JSONObject.parseArray(pictureSet, String.class));
					}
					res.setUser(userService.getById(res.getUserId()));
					i.setRes(res);
				}
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
			});
		}
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), records);
	}

	/**
	 * 收藏列表
	 * 
	 * @return
	 */
	@GetMapping("/colllist")
	public LayuiResult<Object> colllist() {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Page<ZpCollect> page = startPage();
		ZpCollect collect = new ZpCollect();
		collect.setUserId(wxUser.getUser().getUserId());
		Page<ZpCollect> pageList = collectService.pageList(page, collect);
		List<ZpCollect> records = pageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				ZpResources res = resourcesService.getById(i.getArticleId());
				if (ToolUtil.isNotEmpty(res)) {
					// 是否点赞
					int voteCount = voteService.count(new QueryWrapper<ZpVote>()
							.eq("user_id", wxUser.getUser().getUserId()).eq("article_id", res.getArticleId()));
					res.setVote(voteCount > 0);
					res.setCommentNum(commentService.getCommentNum(res.getArticleId().toString()));
					// 阅读量格式化
					res.setReadSizeFormat(NumberUtils.amountConversion(res.getReadSize()));
					// 点赞量格式化
					res.setVoteSizeFormat(NumberUtils.amountConversion(res.getVoteSize()));
					String pictureSet = res.getPictureSet();
					if (StrUtil.isNotEmpty(pictureSet)) {
						// 图片数据封装
						res.setImgs(JSONObject.parseArray(pictureSet, String.class));
					}
					res.setUser(userService.getById(res.getUserId()));
					i.setRes(res);
				}
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
			});
		}
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), records);
	}

	/**
	 * 浏览历史列表
	 * 
	 * @return
	 */
	@GetMapping("/historys")
	public LayuiResult<Object> historys() {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Page<ZpHistory> page = startPage();
		ZpHistory history = new ZpHistory();
		history.setUserId(wxUser.getUser().getUserId());
		Page<ZpHistory> pageList = historyService.pageList(page, history);
		List<ZpHistory> records = pageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				ZpResources res = resourcesService.getById(i.getArticleId());
				if (ToolUtil.isNotEmpty(res)) {
					// 是否点赞
					int voteCount = voteService.count(new QueryWrapper<ZpVote>()
							.eq("user_id", wxUser.getUser().getUserId()).eq("article_id", res.getArticleId()));
					res.setVote(voteCount > 0);
					res.setCommentNum(commentService.getCommentNum(res.getArticleId().toString()));
					// 阅读量格式化
					res.setReadSizeFormat(NumberUtils.amountConversion(res.getReadSize()));
					// 点赞量格式化
					res.setVoteSizeFormat(NumberUtils.amountConversion(res.getVoteSize()));
					String pictureSet = res.getPictureSet();
					if (StrUtil.isNotEmpty(pictureSet)) {
						// 图片数据封装
						res.setImgs(JSONObject.parseArray(pictureSet, String.class));
					}
					res.setUser(userService.getById(res.getUserId()));
					i.setRes(res);
				}
				i.setTime(DateUtil.format(i.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN));
			});
		}
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), records);
	}

	/**
	 * 用户关注列表
	 * 
	 * @param key 查询关键词
	 * @return
	 */
	@GetMapping("/followlist")
	public LayuiResult<Object> followlist(@RequestParam(required = false) String key) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Page<FollowVo> page = startPage();
		Long userId = wxUser.getUser().getUserId();
		Page<FollowVo> pageLisst = followService.followlist(page, userId, key);
		List<FollowVo> records = pageLisst.getRecords();
		Map<String, Object> map = new HashMap<>();
		List<FollowVo> rec = new ArrayList<>();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				i.setMutual(true);
				// 粉丝数量
				i.setFans(ConstantFactory.me().getFans(i.getUserId()));
			});
		} else if (StrUtil.isNotEmpty(key)) {
			Page<SysUser> pageu = new Page<>(1, 5);
			Page<SysUser> userPage = userService.reclike(pageu, userId, key);
			List<SysUser> records2 = userPage.getRecords();
			if (ToolUtil.isNotEmpty(records2)) {
				rec = records2.stream().map(i -> {
					FollowVo f = new FollowVo();
					f.setAvatar(i.getAvatar());
					f.setMutual(false);
					f.setFans(ConstantFactory.me().getFans(i.getUserId()));
					f.setNickName(i.getNickName());
					f.setUserId(i.getUserId());
					return f;
				}).collect(Collectors.toList());
			}
		}
		map.put("res", records);
		map.put("rec", rec);
		return LayuiResult.success(pageLisst.hasNext(), pageLisst.getTotal(), map);
	}

	/**
	 * 用户粉丝列表
	 * 
	 * @param key 查询关键词
	 * @return
	 */
	@GetMapping("/fanslist")
	public LayuiResult<Object> fanslist(@RequestParam(required = false) String key) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long userId = wxUser.getUser().getUserId();
		Page<FollowVo> page = startPage();
		Page<FollowVo> pageLisst = fansService.fanslist(page, userId, key);
		List<FollowVo> records = pageLisst.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			records.forEach(i -> {
				i.setMutual(ConstantFactory.me().mutual(i.getUserId(), userId));
				// 粉丝数量
				i.setFans(ConstantFactory.me().getFans(i.getUserId()));
			});
		}
		return LayuiResult.success(pageLisst.hasNext(), pageLisst.getTotal(), records);
	}

	/**
	 * 获取用户信息
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/user/{id}")
	public Result<Object> userInfo(@PathVariable String id) {
		SysUser byId = userService.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("该用户不存在");
		}
		Long userId = byId.getUserId();
		// 获取粉丝量
		byId.setFans(ConstantFactory.me().getFans(userId));
		// 获取关注量
		byId.setFollow(ConstantFactory.me().getAttention(userId));
		// 获取获赞量
		byId.setBePraised(ConstantFactory.me().getBePraised(userId));
		// 获取发布量
		byId.setReleaseVolume(ConstantFactory.me().getReleaseVolume(userId));
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isNotEmpty(wxUser)) {
			byId.setMutual(ConstantFactory.me().mutual(userId, wxUser.getUser().getUserId()));
		}
		return Result.success(byId);
	}

	/**
	 * 聊天列表
	 * 
	 * @return
	 */
	@GetMapping("/chatlist")
	public LayuiResult<Object> chatlist() {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		Long userId = wxUser.getUser().getUserId();
		QueryWrapper<ZpChatList> queryWrapper = new QueryWrapper<>();

		queryWrapper.eq("user_id", userId);
		queryWrapper.orderByDesc("create_time");
		List<ZpChatList> list = chatListService.list(queryWrapper);
		List<CathListVo> collect = new ArrayList<>();
		if (ToolUtil.isNotEmpty(list)) {
			collect = list.stream().map(i -> {
				CathListVo vo = new CathListVo();
				vo.setId(i.getLid());
				Long anotherId = i.getAnotherId();
				SysUser byId = userService.getById(anotherId);
				if (ToolUtil.isNotEmpty(byId)) {
					vo.setUserId(byId.getUserId());
					vo.setAvatar(byId.getAvatar());
					vo.setNickName(byId.getNickName());
				}
				vo.setTime(DateUtil.timeToFormatchat(i.getCreateTime()));
				vo.setUnread(i.getUnread());
				// 最后一条消息
				ZpChatMsg one = chatMsgService.getOne(new QueryWrapper<ZpChatMsg>()
						.and(n -> n.eq("user_id", i.getUserId()).eq("rec_user_id", i.getAnotherId()).eq("latest", "0"))
						.or().eq("user_id", i.getAnotherId()).eq("rec_user_id", i.getUserId()).eq("latest", "0"),
						false);
				if (ToolUtil.isNotEmpty(one)) {
					vo.setMsg(one.getContent());
					vo.setTime(DateUtil.timeToFormatchat(one.getCreateTime()));
					vo.setUpdateTime(one.getCreateTime());
				} else {
					vo.setTime(DateUtil.timeToFormatchat(i.getCreateTime()));
					vo.setUpdateTime(i.getCreateTime());
				}
				return vo;
			}).collect(Collectors.toList());
		}
		Collections.sort(collect, Comparator.comparing(CathListVo::getUpdateTime).reversed());
		return LayuiResult.success(false, collect.size(), collect);
	}

	/**
	 * 获取对话列表
	 * 
	 * @return
	 */
	@GetMapping("/chatMsgList/{lid}")
	public LayuiResult<Object> chatMsgList(@PathVariable Long lid) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		List<ChatMsgVo> collect = new ArrayList<>();
		ZpChatList clist = chatListService.getById(lid);
		if (ToolUtil.isEmpty(clist)) {
			return LayuiResult.success(false, 0, collect);
		}
		Long userId = wxUser.getUser().getUserId();
		Page<ZpChatMsg> page = startPage();
		QueryWrapper<ZpChatMsg> queryWrapper = new QueryWrapper<>();
		queryWrapper.ge("create_time", clist.getCreateTime());
		queryWrapper.and(n -> n.eq("user_id", clist.getUserId()).eq("rec_user_id", clist.getAnotherId())).or()
				.eq("user_id", clist.getAnotherId()).eq("rec_user_id", clist.getUserId())
				.ge("create_time", clist.getCreateTime());
		queryWrapper.orderByDesc("mcid", "create_time");
		Page<ZpChatMsg> pageList = chatMsgService.page(page, queryWrapper);
		List<ZpChatMsg> records = pageList.getRecords();
		if (ToolUtil.isNotEmpty(records)) {
			collect = records.stream().map(i -> {
				Long uid = i.getUserId();
				ChatMsgVo vo = new ChatMsgVo();
				vo.setContent(i.getContent());
				vo.setTime(DateUtil.timeToFormatchat(i.getCreateTime()));
				vo.setRecUserId(i.getRecUserId());
				vo.setUserId(uid);
				vo.setMid(i.getMcid());
				if (uid.equals(userId)) {
					vo.setMy(true);
					vo.setAvatar(wxUser.getUser().getAvatar());
				} else {
					SysUser byId = userService.getById(uid);
					vo.setMy(false);
					if (ToolUtil.isNotEmpty(byId)) {
						vo.setAvatar(byId.getAvatar());
					}
				}
				vo.setStatus("1");
				return vo;
			}).collect(Collectors.toList());
		}
		// 更新 未读消息为0
		clist.setUnread(0);
		chatListService.updateById(clist);
		Collections.sort(collect, Comparator.comparing(ChatMsgVo::getMid));
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), collect);
	}

	/**
	 * 删除列表
	 * 
	 * @return
	 */
	@GetMapping("/delChat/{id}")
	public Result<Object> delChatList(@PathVariable String id) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(chatListService.removeById(id));
	}

	/**
	 * 创建聊天列表
	 * 
	 * @param uid
	 * @return
	 */
	@GetMapping("/createChat/{uid}")
	public Result<Object> createChat(@PathVariable Long uid) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		List<ZpChatList> list = chatListService
				.list(new QueryWrapper<ZpChatList>().eq("user_id", wxUser.getUser().getUserId()).eq("another_id", uid));
		if (ToolUtil.isNotEmpty(list) && list.size() == 1) {
			return Result.success(list.get(0).getLid());
		} else {
			chatListService.remove(
					new QueryWrapper<ZpChatList>().eq("user_id", wxUser.getUser().getUserId()).eq("another_id", uid));
			ZpChatList chat = new ZpChatList();
			chat.setUserId(wxUser.getUser().getUserId());
			chat.setAnotherId(uid);
			chat.setUnread(0);
			chat.setUserOnline("1");
			chatListService.save(chat);
			return Result.success(chat.getLid());
		}
	}

	/**
	 * 个性标签
	 * 
	 * @return
	 */
	@GetMapping("/hotlabel")
	public Result<Object> hotlabel() {
		Page<ZpLabel> labels = labelService.pageList(1, 14, new ZpLabel());
		return Result.success(labels.getRecords());
	}

	/**
	 * 帮助找铺
	 * 
	 * @param helpShop
	 * @return
	 */
	@GetMapping("/helpshop")
	public Result<Object> helpshop(@Validated ZpHelpShop helpShop) {
		return Result.success(helpShopService.save(helpShop));
	}

	/**
	 * 添加意见反馈
	 * 
	 * @param helpShop
	 * @return
	 */
	@GetMapping("/feedback")
	public Result<Object> feedback(@Validated ZpFeedback feedback) {
		return Result.success(feedbackService.add(feedback));
	}

	/**
	 * 修改头像
	 * 
	 * @param avatar
	 * @return
	 */
	@GetMapping("/editavatar")
	public Result<Object> editavatar(@RequestParam String avatar) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser byId = userService.getById(wxUser.getUser().getUserId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		byId.setAvatar(avatar);
		return Result.success(userService.updateById(byId));
	}

	/**
	 * 修改用户名
	 * 
	 * @param nickName
	 * @return
	 */
	@GetMapping("/editnickname")
	public Result<Object> editnickname(@RequestParam String nickName) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		boolean examineText = TextContent.examineText(nickName);
		if (examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		SysUser byId = userService.getById(wxUser.getUser().getUserId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		byId.setNickName(nickName);
		return Result.success(userService.updateById(byId));
	}

	/**
	 * 修改简介
	 * 
	 * @param profiles
	 * @return
	 */
	@GetMapping("/editprofiles")
	public Result<Object> editprofiles(@RequestParam String profiles) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser byId = userService.getById(wxUser.getUser().getUserId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		boolean examineText = TextContent.examineText(profiles);
		if (examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		byId.setRemark(profiles);
		return Result.success(userService.updateById(byId));
	}

	/**
	 * 修改性别
	 * 
	 * @param sex
	 * @return
	 */
	@GetMapping("/editsex")
	public Result<Object> editsex(@RequestParam String sex) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser byId = userService.getById(wxUser.getUser().getUserId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		byId.setSex(sex);
		return Result.success(userService.updateById(byId));
	}

	/**
	 * 修改手机号
	 * 
	 * @param profiles
	 * @return
	 */
	@PostMapping("/editphose")
	public Result<Object> editphose(@Validated @RequestBody EditPhoneForm editPhoneForm) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser byId = userService.getById(wxUser.getUser().getUserId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		String oldPhone = editPhoneForm.getOldPhone();
		if (!StrUtil.equals(oldPhone, byId.getUserName())) {
			throw new CustomException("输入的当前绑定手机号不正确", 400);
		}
		String uuid = editPhoneForm.getUuid();
		String code = editPhoneForm.getCode();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!StrUtil.equalsIgnoreCase(code, captcha)) {
			throw new CaptchaException();
		}
		byId.setUserName(editPhoneForm.getNewPhone());
		byId.setPhonenumber(editPhoneForm.getNewPhone());
		return Result.success(userService.updateById(byId));
	}

	/**
	 * 修改密码
	 * 
	 * @param profiles
	 * @return
	 */
	@PostMapping("/editpasswod")
	public Result<Object> editpasswod(@Validated @RequestBody EditPwdForm editPwdForm) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser byId = userService.getById(wxUser.getUser().getUserId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		String uuid = editPwdForm.getUuid();
		String code = editPwdForm.getCode();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!StrUtil.equalsIgnoreCase(code, captcha)) {
			throw new CaptchaException();
		}
		byId.setPassword(SecurityUtils.encryptPassword(editPwdForm.getPassword()));
		return Result.success(userService.updateById(byId));
	}

	// 生日

	// 地区

	/**
	 * 默认头像列表
	 * 
	 * @return
	 */
	@GetMapping("/defaultavatar")
	public Result<Object> defaultavatar() {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		List<ZpAvatar> list = avatarService.list();
		Map<String, List<ZpAvatar>> resultList = list.stream().collect(Collectors.groupingBy(ZpAvatar::getGroupId));
		return Result.success(resultList);
	}

	/**
	 * 头像上传
	 */
	@PostMapping("/avatar")
	public Result<Object> avatar(MultipartFile file) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser user = wxUser.getUser();
		if (!file.isEmpty()) {
			String bucketName = CrawlerConfig.getBucketName();
			Long loginUserId = user.getUserId();
			String extension = FileUploadUtils.getExtension(file);
			String fileName = IdUtil.simpleUUID() + "." + extension;
			String key = Constants.AVATAR_KEY + fileName;
			String redisKey = Constants.UPLOAD_PROGRESS + loginUserId + ":" + IdUtil.simpleUUID();
			cosPutObject.put(file, bucketName, key, redisKey);
			String avatar = Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/"
					+ Constants.AVATAR_KEY + fileName;
			String username = user.getUserName();
			userService.updateUserAvatar(username, avatar);
			return Result.success("ok");
		}
		return Result.error("上传失败");
	}

	/**
	 * 问题咨询列表
	 * 
	 * @return
	 */
	@GetMapping("/qtypelist")
	public Result<Object> qtypelist() {
		return Result.success(questionTypeService.list());
	}

	/**
	 * 问题详情
	 * 
	 * @return
	 */
	@GetMapping("/qdetails/{id}")
	public Result<Object> qdetails(@PathVariable String id) {
		ZpQuestion i = questionService.getById(id);
		if (ToolUtil.isNotEmpty(i)) {
			QuestionVo questionVo = new QuestionVo();
			ZpQuestionType byId = questionTypeService.getById(i.getQuestionType());
			if (ToolUtil.isNotEmpty(byId)) {
				questionVo.setTage(byId.getQuestionType()); // 咨询类别标签
			}
			SysUser user = ConstantFactory.me().getUser(i.getConsultant());
			if (ToolUtil.isNotEmpty(user)) {
				questionVo.setAvatar(user.getAvatar()); // 头像
				questionVo.setName(user.getNickName()); // 咨询师姓名
				questionVo.setGraduateSchool(user.getRemark()); // 毕业学校
			}
			questionVo.setId(i.getId());
			questionVo.setUserName(i.getUserName()); // 咨询用户
			questionVo.setQuestion(i.getQuestion()); // 问题
			questionVo.setAnswer(i.getAnswer()); // 解答
			questionVo.setAnswerTime(i.getAnswerTime()); // 解答时间
			questionVo.setFabulous(i.getFabulous()); // 点赞数量
			int count = questionService.count(new QueryWrapper<ZpQuestion>().eq("consultant", i.getConsultant()));
			questionVo.setZxrs(count); // 咨询人数
			questionVo.setConsultant(i.getConsultant());
			questionVo.setTime(DateUtil.timeToFormat(i.getCreateTime()));
			return Result.success(questionVo);
		} else {
			return Result.error();
		}
	}
	
	/**
	 * 获取草稿箱列表
	 * @return
	 */
	@GetMapping("/drafts")
	public LayuiResult<Object> draft(){
		Page<ZpResources> page = startPage();	
		QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("draft", 1);
		queryWrapper.orderByDesc("create_time");
		Page<ZpResources> pageList = resourcesService.page(page, queryWrapper);
		new ZpResourcesWrapper(pageList).wrap();
		return LayuiResult.success(pageList.hasNext(), pageList.getTotal(), pageList.getRecords());
	}
	
	/**
	 * 内容基础详情
	 * @param id
	 * @return
	 */
	@GetMapping("/basicdetails/{id}")
	public Result<Object> basicdetails(@PathVariable String id){
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(resourcesService.getById(id));
	}
	
	/**
	 * 经营业态
	 * @return
	 */
	@GetMapping("/format")
	public Result<Object> format(){
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(formatService.list());
	}
	
	/**
	 * 服务类型
	 * @return
	 */
	@GetMapping("/serviceitems")
	public Result<Object> serviceitems(){
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(serviceItemsService.list());
	}
	
	/**
	 * 文本检测
	 * @param content
	 * @return
	 */
	@GetMapping("/textReview")
	public Result<Object> textReview(@RequestParam(required = false) String content) {
		if(StrUtil.isEmpty(content)) {
			return Result.error("文本内容为空");
		}
		ServiceResult<Object> result = TextContent.examineTextres(content);
		if(result.isSuccess()) {
			return Result.success("检测通过");
		}else {
			return Result.error(result.getMessage());
		}
	}
	
	/**
	 *立即发布资源
	 * @param id 资源ID
	 * @return
	 */
	@PostMapping("/publish/{id}")
	@Log(title = "发布资源", businessType = BusinessType.UPDATE)
	public Result<Object> publish(@PathVariable String id){
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		return Result.success(resourcesService.wxpublish(wxUser.getUser(), id));
	}
	
	/**
	 * 发布视频
	 * @param videoVo
	 * @param uploadFile
	 * @return
	 */
	@PostMapping("/video")
	@Log(title = "发布资源", businessType = BusinessType.INSERT)
	public Result<Object> video(MultipartFile uploadFile, @Validated VideoVo videoVo){
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		boolean title = TextContent.examineText(videoVo.getTitle());
		if (title) {
			return Result.error("发布内容含敏感词汇");
		}
		String contentText = videoVo.getContent();
		boolean examineText = TextContent.examineText(contentText);
		if (examineText) {
			return Result.error("发布内容含敏感词汇");
		}
		ResourcesForm resources = new ResourcesForm();
		Long userId = wxUser.getUser().getUserId();
		resources.setUserId(userId);
		if(ToolUtil.isEmpty(uploadFile)) {
			return Result.error(HttpStatus.BAD_REQUEST, "请上传文件");
		}
		String bucketName = CrawlerConfig.getBucketName();
		Long loginUserId = userId;
		String extension = FileUploadUtils.getExtension(uploadFile);
		String fileName = IdUtil.simpleUUID() + "." + extension;
		String key = Constants.VIDEO_KEY + fileName;
		String redisKey = Constants.UPLOAD_PROGRESS + loginUserId + ":" + IdUtil.simpleUUID();
		String etag = cosPutObject.put(uploadFile,bucketName , key, redisKey);
		String url = Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/" + Constants.VIDEO_KEY + fileName;
		String mediaPicPath = CrawlerConfig.getImgCoverPath() + IdUtil.simpleUUID() + ".jpg";
		//截取封面图
		String coverUrl = ""; 
		try {
			VideoUtils.fetchFrameUrl(url, mediaPicPath, 1);
			String imgFileName = IdUtil.simpleUUID() + ".jpg";
			String imgkey = Constants.IMG_KEY + imgFileName;
			cosPutObject.localPut(mediaPicPath, bucketName, imgkey);
			coverUrl = Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/" + Constants.IMG_KEY + imgFileName;
			File file = new File(mediaPicPath);
			if(file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
			log.error("截取视频封面失败");
		}
		File file = new File(mediaPicPath);
		if(file.exists()) {
			file.delete();
		}
		
		redisCache.deleteObject(redisKey);
		redisCache.deleteObject(redisKey + "_percentage");
				
    	String content =  "<p>" + contentText + "<p><div id='v_"+ etag +"'><video id='"+ etag +"' poster='"+ coverUrl +"' controls='controls' width='512' height='384'>"+
    			"<source src='"+ url +"' type='video/mp4' />"+
    		"</video></div>";		
    	resources.setTitle(videoVo.getTitle());
    	resources.setContentText(contentText);
    	resources.setContent(content);
    	resources.setDraft("0");
    	resources.setColumnId(1);
    	PublishRes publishRes = resourcesService.wxadd(resources);
		return Result.success(publishRes);
	}
	
	/**
	 * 生日
	 * @return
	 */
	@GetMapping("/birthday")
	public Result<Object> birthday(@RequestParam String birthday) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser user = wxUser.getUser();
		SysUser byId = userService.getById(user.getUserId());
		if(ToolUtil.isNotEmpty(byId)) {
			byId.setBirthday(birthday);
		}
		return Result.success(userService.updateById(byId));
	}
	
	/**
	 * 地区
	 * @return
	 */
	@GetMapping("/region")
	public Result<Object> region(@RequestParam String region) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser user = wxUser.getUser();
		SysUser byId = userService.getById(user.getUserId());
		if(ToolUtil.isNotEmpty(byId)) {
			byId.setRegion(region);
		}
		return Result.success(userService.updateById(byId));
	}
	
	/**
	 * 修改背景图
	 */
	@PostMapping("/backmap")
	public Result<Object> backmap(MultipartFile file) {
		LoginUser wxUser = tokenService.getWxUser();
		if (ToolUtil.isEmpty(wxUser)) {
			throw new CustomException("未登录", HttpStatus.UNAUTHORIZED);
		}
		SysUser user = wxUser.getUser();
		SysUser byId = userService.getById(user.getUserId());
		if(ToolUtil.isEmpty(byId)) {
			throw new CustomException("非法用户");
		}
		
		if (!file.isEmpty()) {
			String bucketName = CrawlerConfig.getBucketName();
			Long loginUserId = user.getUserId();
			String extension = FileUploadUtils.getExtension(file);
			String fileName = IdUtil.simpleUUID() + "." + extension;
			String key = Constants.AVATAR_KEY + fileName;
			String redisKey = Constants.UPLOAD_PROGRESS + loginUserId + ":" + IdUtil.simpleUUID();
			cosPutObject.put(file, bucketName, key, redisKey);
			String backmap = Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/"
					+ Constants.AVATAR_KEY + fileName;
			byId.setBackmap(backmap);
			userService.updateById(byId);
			return Result.success(backmap);
		}
		return Result.error("上传失败");
	}
	
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("content", "<p>在也是有<img src=''></img></p><p><br></p>");
		map.put("qewq", "qeq");
		System.out.println(JSONObject.parseObject(JSONObject.toJSONString(map), ResourcesForm.class));
	}

}
